package com.anyikang.volunteer.sos.volunteer.utils;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;

import com.anyikang.volunteer.sos.volunteer.R;
import com.anyikang.volunteer.sos.volunteer.app.bean.Device;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.utils.CoordinateConverter;
import com.baidu.mapapi.utils.DistanceUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 百度地图工具类
 *
 * @author xw.gao
 * @version 2017/6/12
 * @git http://60.205.139.138:81/root/GSMServerAPP.git
 */

public class BaiduMapUtils {

    private static MarkerOptions endMarker;
    private static Polyline mPolyline;
    private static MapStatusUpdate msUpdate;
    private static PolylineOptions polylineOptions;
    private static Polyline mVirtureRoad;
    private static MarkerOptions startMarker;

    /**
     * 根据经纬度添加图片覆盖物
     *
     * @param mBaiduMap 百度地图对象
     * @param latitude  纬度
     * @param longitude 经度
     */
    public static void addOverlay(BaiduMap mBaiduMap, double latitude, double longitude, Device device, String chatGrpId) {
        LatLng llA = new LatLng(latitude, longitude);
        CoordinateConverter converter = new CoordinateConverter();
        converter.coord(llA);
        converter.from(CoordinateConverter.CoordType.GPS);
        LatLng convertLatLng = converter.convert();//如果坐标已经是百度坐标类型了，那就不应该再转换了，否则又会偏移
        MarkerOptions ooA = new MarkerOptions().position(convertLatLng).icon(BitmapDescriptorFactory
                .fromResource(R.drawable.icon_marka))
                .zIndex(4).draggable(true);

        ooA.animateType(MarkerOptions.MarkerAnimateType.grow);
        Marker marker = (Marker) mBaiduMap.addOverlay(ooA);

        /*gxw+s*/
        Bundle bundle = new Bundle();
        bundle.putString("deviceIMEI",device.getDeviceIMEI());
        bundle.putInt("alarmType",device.getAlarmType());
        bundle.putString("groupId",chatGrpId);
        bundle.putDouble("lat",latitude);
        bundle.putDouble("lng",longitude);
        bundle.putString("loctime",device.getLocationTime());
        marker.setExtraInfo (bundle);
        /*gxw+e*/

        MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(convertLatLng, 14.0f);
        mBaiduMap.animateMapStatus(u);
    }

    /**
     * 绘制轨迹
     *
     * @param
     */
    public static void drawTrack(Context mContext, BaiduMap mBaiduMap, final List<LatLng> polylines) {
        // 绘制新覆盖物前，清空之前的覆盖物
        mBaiduMap.clear();
        if (polylines.size() == 1) {
            polylines.add(polylines.get(0));
        }
        if (polylines == null || polylines.size() == 0) {
            ToastUtils.showToast(mContext, "当前查询无轨迹点");
        } else if (polylines.size() > 1) {
            LatLng llStart = polylines.get(0);
            LatLng llEnd = polylines.get(polylines.size() - 1);
            LatLngBounds bounds = new LatLngBounds.Builder().include(llStart).include(llEnd).build();
            msUpdate = MapStatusUpdateFactory.newLatLngBounds(bounds);
            // 添加路线（轨迹）
            PolylineOptions polylineOptions = new PolylineOptions().points(polylines).width(15).color(Color.BLUE);
            mPolyline = (Polyline) mBaiduMap.addOverlay(polylineOptions);
            // 添加起点图标
            startMarker = new MarkerOptions().flat(true).anchor(0.5f, 0.5f)
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_marka)).position(polylines.get(0))
                    .rotate((float) getAngle(0));
            mBaiduMap.addOverlay(startMarker);
            // 添加起点图标
            CircleOptions circleOptions = new CircleOptions();
            circleOptions.center(polylines.get(0));
            circleOptions.radius(100);
            circleOptions.fillColor(Color.argb(10,255,0,255));
            mBaiduMap.addOverlay(circleOptions);
            // 添加终点图标
            endMarker = new MarkerOptions().flat(true).anchor(0.5f, 0.5f)
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_marka)).position(polylines.get(polylines.size() - 1));
            mBaiduMap.addOverlay(endMarker);
        }

    }

    /**
     * 根据点获取图标转的角度
     */
    private static double getAngle(int startIndex) {
        if ((startIndex + 1) >= mPolyline.getPoints().size()) {
            throw new RuntimeException("index out of bonds");
        }
        LatLng startPoint = mPolyline.getPoints().get(startIndex);
        LatLng endPoint = mPolyline.getPoints().get(startIndex + 1);
        return getAngle(startPoint, endPoint);
    }

    /**
     * 根据两点算取图标转的角度
     */
    private static double getAngle(LatLng fromPoint, LatLng toPoint) {
        double slope = getSlope(fromPoint, toPoint);
        if (slope == Double.MAX_VALUE) {
            if (toPoint.latitude > fromPoint.latitude) {
                return 0;
            } else {
                return 180;
            }
        }
        float deltAngle = 0;
        if ((toPoint.latitude - fromPoint.latitude) * slope < 0) {
            deltAngle = 180;
        }
        double radio = Math.atan(slope);
        double angle = 180 * (radio / Math.PI) + deltAngle - 90;
        return angle;
    }

    /**
     * 算斜率
     */
    private static double getSlope(LatLng fromPoint, LatLng toPoint) {
        if (toPoint.longitude == fromPoint.longitude) {
            return Double.MAX_VALUE;
        }
        double slope = ((toPoint.latitude - fromPoint.latitude) / (toPoint.longitude - fromPoint.longitude));
        return slope;

    }

    /**
     * 处理轨迹
     * 判断是否是某一天的第一个点
     * 两点之间的距离是否大于1m
     * 两点之间的距离是否小于120m
     */
    public static List<LatLng> getTrack(List<LatLng> mList) {
        List<LatLng> nList = new ArrayList<>();
        if (mList != null && mList.size() > 0) {
            nList.add(mList.get(0));
            for (int i = 0; i < mList.size() - 1; i++) {
                if (getDistance(mList.get(i), mList.get(i + 1)) > 1 && getDistance(mList.get(i), mList.get(i + 1)) < 120) {
                    nList.add(mList.get(i + 1));
                }
            }
        }
        return nList;
    }

    /**
     * 根据经纬度计算两点之间的距离 转换错误时返回-1
     *
     * @param Latlng1
     * @param Latlng2
     */
    public static double getDistance(LatLng Latlng1, LatLng Latlng2) {
        double distance;
        distance = DistanceUtil.getDistance(Latlng1, Latlng2);
        if (distance != -1) {
            return distance;
        }
        return 0;
    }

    /**
     * 将轨迹坐标对象转换为地图坐标对象
     *
     * @param traceLatLng
     * @return
     */
  /* gxw-s public static LatLng convertTrace2Map(com.baidu.trace.model.LatLng traceLatLng) {
        return new LatLng(traceLatLng.latitude, traceLatLng.longitude);
    }gxw-e*/




    /**
     * 将gps坐标转换为地图坐标对象
     *
     * @param lat,lng  GPS
     * @return
     */
    public static LatLng convertGps2Map(double lat, double lng) {
        LatLng llA = new LatLng(lat, lng);
        CoordinateConverter converter = new CoordinateConverter();
        converter.coord(llA);
        converter.from(CoordinateConverter.CoordType.GPS);
        LatLng convertLatLng = converter.convert();//如果坐标已经是百度坐标类型了，那就不应该再转换了，否则又会偏移


        return convertLatLng;
    }
}
